package com.xy_pro.xymanager.controller;

import com.xy_pro.xymanager.auth.dto.ResultResponse;
import com.xy_pro.xymanager.entity.UserEntity;
import com.xy_pro.xymanager.payload.ErrorResponse;
import com.xy_pro.xymanager.repository.UserRepository;
import com.xy_pro.xymanager.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.web.PagedResourcesAssembler;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.PagedModel;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserRepository  userRepository;

    @Autowired
    private UserService userService;

    private Logger logger = LoggerFactory.getLogger(UserController.class);

//    @Autowired
//    private final PagedResourcesAssembler<UserEntity> pagedResourcesAssembler;

//    @Autowired
//    private final PagedResourcesAssembler<UserEntity> pagedResourcesAssembler;

    // 添加或更新学生密码
    @PostMapping("/saveUser")
//    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> saveUser(@RequestBody UserEntity userEntity) {

        UserEntity entity = userService.saveUser(userEntity);
        if(entity != null){
            return ResponseEntity.ok(entity);
        } else {
            ErrorResponse error = new ErrorResponse("请传入正确的用户信息");
            return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
        }
    }

    // 获取所有学生
    @GetMapping("/allUser")
    @PreAuthorize("hasRole('ADMIN')")
    public ResultResponse<PagedModel<EntityModel<UserEntity>>> getAllUser(@RequestParam(required = false) String username,
                                                       @RequestParam(defaultValue = "1") Integer currentPage,
                                                       @RequestParam(defaultValue = "10") int pageSize,
                                                                          PagedResourcesAssembler<UserEntity> pagedResourcesAssembler) {
        logger.info("getAllUser userName:{}, currentPage: {}, pageSize:{}", username, currentPage, pageSize);
        Page<UserEntity> userPage = userService.getUsers(username, currentPage, pageSize);
        PagedModel<EntityModel<UserEntity>> pagedModel = pagedResourcesAssembler.toModel(userPage);
        return ResultResponse.success(pagedModel);
    }

    // 根据姓名获取学生
    @GetMapping("/{name}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<UserEntity> getUserByName(@PathVariable String name) {
        Optional<UserEntity> user = userRepository.findByName(name);
        return user.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build());
    }

    // 删除学生
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
        userRepository.deleteById(id);
        return ResponseEntity.noContent().build();
    }
}
